param(
    [string]$TinyGo = "tinygo",
    [string]$Nasm = "nasm",
    [string]$Linker = "ld.lld",
    [string]$TextAddr = "0x00520000"
)

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

$root = Resolve-Path (Join-Path $PSScriptRoot "..")
$buildDir = Join-Path $root "build"
if (-not (Test-Path $buildDir)) { New-Item -ItemType Directory -Path $buildDir | Out-Null }
$assetsDir = Join-Path $root "cmd\kernel\assets"
if (-not (Test-Path $assetsDir)) { New-Item -ItemType Directory -Path $assetsDir | Out-Null }

$targetFile = Join-Path $root "targets\tinygo-i386.json"
# When building with TinyGo directly to ELF, we don't need a custom entry stub.

# Provide minimal C memory routines required by TinyGo runtime
$supportAsm = Join-Path $root "examples\go\support\memset.asm"
$supportObj = Join-Path $buildDir "tinygo_support.o"
if (Test-Path $supportAsm) {
    & $Nasm "-f" "elf32" "-o" $supportObj $supportAsm
    if ($LASTEXITCODE -ne 0) { throw "NASM failed for tinygo support" }
}

$examplesRoot = Join-Path $root "examples\go"
if (-not (Test-Path $examplesRoot)) { return }

$built = 0
Get-ChildItem -Directory $examplesRoot | ForEach-Object {
    $dir = $_.FullName
    $name = $_.Name
    $goFiles = Get-ChildItem -Path $dir -Filter "*.go" -File -ErrorAction SilentlyContinue
    if (-not $goFiles) { return }
    $elf = Join-Path $buildDir "$name-go.elf"
    $dest = Join-Path $assetsDir "$name-go.elf"

    $extraLd = ""
    if (Test-Path $supportObj) { $extraLd = $supportObj }
    & $TinyGo build -o $elf -target $targetFile -scheduler "none" -panic "trap" -no-debug -ldflags $extraLd $dir
    if ($LASTEXITCODE -ne 0) { throw "TinyGo failed for $name" }

    Copy-Item -Force $elf $dest
    $built++
}

Write-Host "Built $built TinyGo sample(s) into assets"